package com.ultrapower.ctool.xn_app;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.gson.Gson;
import com.hh.timeselector.timeutil.datedialog.TimeConfig;
import com.ultrapower.ctool.ConfUtils;
import com.ultrapower.ctool.core.CustomApplication;
import com.ultrapower.ctool.http.BaseActivity;
import com.ultrapower.ctool.model.RegisterRolePirVO;
import com.ultrapower.ctool.utils.InstanceUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ChangeWgXXActivity extends BaseActivity implements View.OnClickListener {
    private EditText aname_change_wgxx;//社区(村)名称
    private EditText address_change_wgxx;//地址
    private EditText lon_change_wgxx;//经度
    private EditText lat_change_wgxx;//纬度
    private EditText introduce_change_wgxx;//网格介绍
    private EditText person_change_wgxx;//负责人姓名
    private EditText persontel_change_wgxx;//负责人电话
    private Spinner status_change_wgxx;//状态
    private TextView save_change_wgxx;//保存
    private TextView cancle_change_wgxx;//取消
    private ImageView lon_change_wgxx_img;
    private ImageView lat_change_wgxx_img;
    public LocationClient mLocationClient;
    private static final List<RegisterRolePirVO> statuses = new ArrayList<RegisterRolePirVO>();
    private Map<String, Spinner> spinnerMap = new HashMap<String, Spinner>();

    private Map<String, EditText> textMap = new HashMap<String, EditText>();
    private Map<String, Map<String, Object>> resultMap;
    private CustomApplication application;
    //private OkHttpClient client = new OkHttpClient();
    private Gson gson = new Gson();
    private AdapterView.OnItemSelectedListener OnCatSpinnerCL = new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view, int pos,
                                   long id) {
            ((TextView) parent.getChildAt(0)).setTextColor(Color.BLACK);
            ((TextView) parent.getChildAt(0)).setTextSize(18);
        }

        public void onNothingSelected(AdapterView<?> parent) {

        }
    };
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Toast.makeText(getApplicationContext(), "修改成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(ChangeWgXXActivity.this, WangGeXXActivity.class);

                    startActivity(intent);
                    finish();
                    break;
                case 0:
                    Toast.makeText(getApplicationContext(), "系统出现异常", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    static {
        statuses.add(new RegisterRolePirVO("", ""));
        statuses.add(new RegisterRolePirVO("1", "正常"));
        statuses.add(new RegisterRolePirVO("2", "停用"));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_wgxx);
        init();
        //根据ID查询后台数据
        Intent intent = getIntent();
        System.out.println(intent.getStringExtra("xid"));
        getWangGeInfo(intent.getStringExtra("xid"));
    }

    private void getWangGeInfo(final String xid) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response = null;
                Request request = null;
                try {
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("userId", String.valueOf(application.getLoginUser().getLogin_id()))
                            .build();
                    request = new Request.Builder().url(ConfUtils.SERVICE_URL + "app_grid/update/c_aj_wgxx-" + xid).post(requestBody).build();
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {//成功
                        String result = response.body().string();
                        resultMap = gson.fromJson(result, Map.class);
                        System.out.println(resultMap);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                for (final Map.Entry<String, Object> entry : resultMap.get("result").entrySet()) {
                                    if (textMap.get(entry.getKey()) != null) {
                                        textMap.get(entry.getKey()).setText(entry.getValue().toString());
                                        textMap.get(entry.getKey()).setEnabled ((Boolean) resultMap.get("result").get(entry.getKey()+"_qx"));
                                        textMap.get(entry.getKey()).setFocusable ((Boolean) resultMap.get("result").get(entry.getKey()+"_qx"));

                                    }
                                }
                                ArrayAdapter<RegisterRolePirVO> aradapter = new ArrayAdapter<RegisterRolePirVO>(getApplicationContext(), android.R.layout.simple_spinner_item, statuses);
                                aradapter.setDropDownViewResource(R.layout.simple_dropdown_item_1line);
                                status_change_wgxx.setAdapter(aradapter);
                                final int k = aradapter.getCount();
                                status_change_wgxx.setOnItemSelectedListener(OnCatSpinnerCL);
                                System.out.println(resultMap);
                                for (int i = 0; i < k; i++) {
                                    if (resultMap.get("result").get("status").equals(aradapter.getItem(i).getId().toString())) {
                                        status_change_wgxx.setSelection(i);
                                        break;
                                    }
                                }
                            }
                        });
                        for(Map.Entry<String, Spinner> entry1 : spinnerMap.entrySet()){
                            entry1.getValue().setEnabled ((Boolean) resultMap.get("result").get(entry1.getKey()+"_qx"));
                            entry1.getValue().setFocusable ((Boolean) resultMap.get("result").get(entry1.getKey()+"_qx"));
                        }
                    } else {
                        Message message = new Message();
                        message.what = 0;
                        handler.sendMessage(message);
                    }
                } catch (Exception e) {
                    Message message = new Message();
                    message.what = 0;
                    handler.sendMessage(message);
                    e.printStackTrace();
                } finally {
                    if (response != null) response.close();

                }
            }
        }).start();
    }

    protected void init() {
        application = (CustomApplication) getApplication();
        aname_change_wgxx = (EditText) findViewById(R.id.aname_change_wgxx);
        textMap.put("aname", aname_change_wgxx);
        address_change_wgxx = (EditText) findViewById(R.id.address_change_wgxx);
        textMap.put("address", address_change_wgxx);
        lon_change_wgxx = (EditText) findViewById(R.id.lon_change_wgxx);
        textMap.put("lon", lon_change_wgxx);
        lat_change_wgxx = (EditText) findViewById(R.id.lat_change_wgxx);
        textMap.put("lat", lat_change_wgxx);
        introduce_change_wgxx = (EditText) findViewById(R.id.introduce_change_wgxx);
        textMap.put("introduce", introduce_change_wgxx);
        person_change_wgxx = (EditText) findViewById(R.id.person_change_wgxx);
        textMap.put("person", person_change_wgxx);
        persontel_change_wgxx = (EditText) findViewById(R.id.persontel_change_wgxx);
        textMap.put("persontel", persontel_change_wgxx);
        status_change_wgxx = (Spinner) findViewById(R.id.status_change_wgxx);
        spinnerMap.put("status", status_change_wgxx);
        save_change_wgxx = (TextView) findViewById(R.id.save_change_wgxx);
        cancle_change_wgxx = (TextView) findViewById(R.id.cancle_change_wgxx);
        lon_change_wgxx_img = (ImageView) findViewById(R.id.lon_change_wgxx_img);
        lat_change_wgxx_img = (ImageView) findViewById(R.id.lat_change_wgxx_img);
        save_change_wgxx.setOnClickListener(this);
        cancle_change_wgxx.setOnClickListener(this);
        lon_change_wgxx_img.setOnClickListener(this);
        lat_change_wgxx_img.setOnClickListener(this);

    }

    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
//        int span = 1000;
//        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
//        option.setOpenGps(false);//可选，默认false,设置是否使用gps
//        option.setLocationNotify(false);//可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
//        option.setIsNeedLocationPoiList(false);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
//        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
//        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤GPS仿真结果，默认需要
        mLocationClient.setLocOption(option);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lon_change_wgxx_img:
                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        if (mLocationClient != null) {
                            mLocationClient.stop();
                        }
                        mLocationClient = new LocationClient(getApplicationContext());
                        mLocationClient.registerLocationListener(new BDLocationListener() {
                            @Override
                            public void onReceiveLocation(final BDLocation bdLocation) {
                                if (bdLocation == null) {
                                    System.out.println("back");
                                    return;
                                }
                                System.out.println("经度:" + bdLocation.getLongitude());
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        lon_change_wgxx.setText(bdLocation.getLongitude() + "");
                                    }
                                });
                            }

                            @Override
                            public void onConnectHotSpotMessage(String s, int i) {

                            }
                        });
                        initLocation();
                        mLocationClient.start();

                    }
                }).start();

                break;
            case R.id.lat_change_wgxx_img:
                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        if (mLocationClient != null) {
                            mLocationClient.stop();
                        }
                        mLocationClient = new LocationClient(getApplicationContext());
                        mLocationClient.registerLocationListener(new BDLocationListener() {
                            @Override
                            public void onReceiveLocation(final BDLocation bdLocation) {
                                if (bdLocation == null) {
                                    System.out.println("back");
                                    return;
                                }
                                System.out.println("纬度:" + bdLocation.getLatitude());
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        lat_change_wgxx.setText(bdLocation.getLatitude() + "");
                                    }
                                });
                            }

                            @Override
                            public void onConnectHotSpotMessage(String s, int i) {
                            }
                        });
                        initLocation();
                        mLocationClient.start();
                    }
                }).start();
                break;
            case R.id.save_change_wgxx:
                String address = address_change_wgxx.getText().toString();
                String lon = lon_change_wgxx.getText().toString();
                String lat = lat_change_wgxx.getText().toString();
                String introduce = introduce_change_wgxx.getText().toString();
                String person = person_change_wgxx.getText().toString();
                String persontel = persontel_change_wgxx.getText().toString();
                String status = ((RegisterRolePirVO) status_change_wgxx.getSelectedItem()).getId();

                if ("".equals(address)
                        || "".equals(lon)
                        || "".equals(lat)
                        || "".equals(introduce)
                        || "".equals(person)
                        || "".equals(persontel)
                        || "".equals(status)
                        ) {
                    Toast.makeText(getApplicationContext(), "请填写完整信息", Toast.LENGTH_SHORT).show();
                } else {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Response response = null;
                            try {
                                OkHttpClient client = new OkHttpClient();
                                //String _id = new DBHelper(changVo).queryBycn(entry.getValue().getText().toString());
                                FormBody.Builder builder = new FormBody.Builder()
                                        .add("userId", String.valueOf(application.getLoginUser().getLogin_id()));
                                for (Map.Entry<String, EditText> entry : textMap.entrySet()) {
                                    resultMap.get("result").put(entry.getKey(), entry.getValue().getText().toString());
                                }

                                for (Map.Entry<String, Object> entry : resultMap.get("result").entrySet()) {
                                    if (entry.getValue() instanceof String) {
                                        builder.add(entry.getKey(), (String) entry.getValue());
                                    }
                                }
                                RequestBody requestBody = builder.build();
                                Request request = new Request.Builder().url(ConfUtils.SERVICE_URL + "form/doUpdate/c_aj_wgxx").post(requestBody).build();
                                response = client.newCall(request).execute();
                                if (response.isSuccessful()) {//成功
                                    String result = response.body().string();
                                    System.out.println("result:" + result);
                                    Map<String, Object> resultMap = gson.fromJson(result, Map.class);
                                    if ((boolean) resultMap.get("success")) {
                                        Message message = new Message();
                                        message.what = 1;
                                        handler.sendMessage(message);
                                    }
                                } else {
                                    Message message = new Message();
                                    message.what = 0;
                                    handler.sendMessage(message);
                                }
                            } catch (Exception e) {
                                Message message = new Message();
                                message.what = 0;
                                handler.sendMessage(message);
                                e.printStackTrace();
                            } finally {
                                if (response != null) response.close();

                            }
                        }
                    }).start();
                }
                break;
            case R.id.cancle_change_wgxx:
//                Intent intent = new Intent(ChangeWgXXActivity.this, WgXXInfoActivity.class);
//                startActivity(intent);
                finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.stop();
        }
    }
}
